#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>

typedef int Key;
typedef int (*HashFunc)(Key);
typedef struct ListNode {
	Key key;
	struct ListNode *pNext;
}	ListNode;

typedef struct Element {
	ListNode *pFirst;
}	Element;

typedef struct HashB {
	Element *pEle;
	int size;
	int capacity;
	HashFunc hashfunc;
}	HashB;

int chuliuyushufa(Key key)
{
	return key % 13;
}

void HashBucketInit(HashB *hashb, int capacity, HashFunc hashfunc)
{
	hashb->pEle = (Element *)malloc(sizeof(Element) * capacity);
	assert(hashb->pEle);
	hashb->size = 0;
	hashb->capacity = capacity;
	hashb->hashfunc = hashfunc;
	memset(hashb->pEle, 0x0, sizeof(Element) * capacity);
}

ListNode *NewSpace(Key key)
{
	ListNode *pNode = (ListNode *)malloc(sizeof(ListNode));
	assert(pNode);
	pNode->key = key;
	pNode->pNext = NULL;
}

void Insert(HashB *hashb, Key key)
{
	assert(hashb);
	int index = hashb->hashfunc(key);

	ListNode *pInsert = hashb->pEle[index].pFirst;
	ListNode *pNode = NewSpace(key);
	assert(pNode);

	pNode->pNext = pInsert;
	pInsert = pNode;
	free(pNode);
	pNode = NULL;
	
//	while(pFind) {
//		pFind = pFind->pNext;
//	}
//
//	pFind = pNode;
	hashb->size++;
}

void Search(Key key, HashB *hashb)
{
	int index = hashb->hashfunc(key);
	if( hashb->pEle[index].pFirst == NULL ) {
		printf("么有找到！！\n");
		return;
	}
	ListNode *pFind = hashb->pEle[index].pFirst;
	while(pFind) {
		if( pFind->key == key ) {
			printf("找见了：%p\n",pFind);
			return;
		}
		pFind = pFind->pNext;
	}
}

void HashBPrint(HashB *hashb)
{
	assert(hashb);
	ListNode *pPrint = NULL;

	int i;
	for( i = 0; i < hashb->capacity; i++ ) {
		pPrint = hashb->pEle[i].pFirst;
		while(pPrint) {
			printf("%2d	%2d\n", pPrint->key, i);
		}
		printf("%2d	%2d\n", pPrint->key, i);
	}
}

int main()
{
	HashB hashb;
	HashBucketInit(&hashb, 13,  chuliuyushufa);
	Insert(&hashb, 3);
	Insert(&hashb, 7);
	Insert(&hashb, 19);
	Insert(&hashb, 25);
	Insert(&hashb, 26);
	Insert(&hashb, 6);
	Insert(&hashb, 12);
	Insert(&hashb, 39);
	Insert(&hashb, 41);
	Insert(&hashb, 32);
	Insert(&hashb, 45);

	HashBPrint(&hashb);
}
